


class ReceivingTicket < ActiveRecord::Base

  belongs_to :rt_proveedor, :class_name => 'RtProveedor', :foreign_key => 'IdRTProveedor'
  accepts_nested_attributes_for :rt_proveedor
  
  belongs_to :rt_transportista, :class_name => 'RtTransportista', :foreign_key => 'IdRTTransportista'
  accepts_nested_attributes_for :rt_transportista
  
  belongs_to :rt_mercancia, :class_name => 'RtMercancia', :foreign_key => 'IdRTMercancia'
  accepts_nested_attributes_for :rt_mercancia
  
  belongs_to :tipo_entrada, :class_name => 'TipoEntrada', :foreign_key => 'IdTipoEntrada'
  #belongs_to :destino, :class_name => 'Destino', :foreign_key => 'IdDestino'
  belongs_to :pais, :class_name => 'Pais', :foreign_key => 'IdDestino'
  belongs_to :cliente, :class_name => 'Cliente', :foreign_key => 'IdCliente'
  
  belongs_to :reexpedicion, :class_name => 'Reexpedicion', :foreign_key => 'IdRTReexpedicion'
  accepts_nested_attributes_for :reexpedicion
  
  has_many :ordenes_compra_rt, :class_name => 'OrdenCompraRt'
  accepts_nested_attributes_for :ordenes_compra_rt
  has_many :ordenes, :through => :ordenes_compra_rt, :source =>:orden, :class_name => "OrdenCompra"
  
  has_many :rt_oc_proveedores
  accepts_nested_attributes_for :rt_oc_proveedores

  has_many :rt_detalles
  has_many :items_rt_detalles,  :through => :rt_detalles, :source =>:item
  has_many :det_ordenes_compra,  :through => :rt_detalles, :source =>:det_orden_compra#, :class_name => 'DetOrdenCompra'
  
  has_one :salida_almacen
  
  
  def self.rts_sin_salida
    rts = ReceivingTicket.all
    rts_ss = []
    rts.each do |rt|
      unless rt.salida_almacen && !rt.salida_almacen.detalles_rt_salida.empty?
        rts_ss << rt
      end
    end
    return rts_ss
  end

  def cantidad_rt
    begin
      total = 0
      self.rt_detalles do |detalle|
        unless detalle.cantidad
          total += detalle.cantidad
        end
      end
      return total
    rescue

      return 0
    end
  end

  def cantidad_salida
    begin
      total = 0
      total = self.salida_almacen.total_bultos
      return total
    rescue
      return 0
    end
  end

  def saldo
    begin

      total = cantidad_rt - cantidad_salida
      return total
    rescue
      return 0
    end
  end



end
